package com.by.hellospringboot.controller;

import com.by.hellospringboot.controller.request.UserRequestBean;
import com.by.hellospringboot.domain.User;
import com.by.hellospringboot.service.TestUserService;
import com.by.hellospringboot.service.UserService;
import org.hibernate.validator.constraints.Range;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;

@Validated
@RestController
@RequestMapping(value = "/user")
public class UserController {

    private final UserService userService;
    private final TestUserService testService;

    public UserController(UserService userService, TestUserService testService) {
        this.userService = userService;
        this.testService = testService;
    }

    @PostMapping(value = "")
    public User create(@RequestBody @Valid UserRequestBean bean) {
        return userService.create(bean);
    }

    @GetMapping(value = "/{id}")
    public User findById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @GetMapping
    public Page<User> list(@RequestParam @Min(value = 0, message = "页数最少为0") int page,
                           @RequestParam @Min(value = 1, message = "每页最少条数为1") int size,
                           @RequestParam(required = false) String username,
                           @RequestParam(required = false) Integer maxAge,
                           @RequestParam(required = false) Integer minAge,
                           @RequestParam(required = false) Integer gender,
                           @RequestParam(required = false) String phone,
                           @RequestParam(required = false) String accessCardNumber,
                           @RequestParam(required = false) String orderParam,
                           @RequestParam(required = false) String direction) {
        return userService.list(page, size, username, maxAge, minAge, gender, phone, accessCardNumber, orderParam, direction);
    }

    @PutMapping(value = "/{id}")
    public User update(@PathVariable Long id, @RequestBody UserRequestBean bean) {
        return userService.update(id, bean);
    }

    @PatchMapping(value = "/{id}")
    public User patch(@PathVariable Long id, @RequestBody UserRequestBean bean) {
        return userService.patch(id, bean);
    }

    @DeleteMapping(value = "/{id}")
    public void delete(@PathVariable Long id) {
        userService.delete(id);
    }

    @GetMapping(value = "/testError")
    public void testError(@RequestParam(required = false) Integer errorCode) {
        testService.testError(errorCode);
    }


}
